﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Data.Entity;
using Microsoft.Practices.Unity;
using C2E2C.Repository;

namespace C2E2C.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private UnityContainer unityContainer;

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Admin",
                "Admin/{action}",
                new { controller = "Admin", action = "Login" }
            );

            routes.MapRoute(
                "Default",
                "{controller}/{action}", 
                new { controller = "Home", action = "Index" }
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ConfigureUnity();
        }

        public IUnityContainer Container
        {
            get { return this.unityContainer; }
        }

        private void ConfigureUnity()
        {
            unityContainer = new UnityContainer();
            unityContainer
                .RegisterInstance<IRepositoryContainer>(
                    new UnityRepositoryContainer(unityContainer, new HttpContextLifetimeManager<DbContext>()));

            ControllerBuilder.Current
                .SetControllerFactory(new UnityControllerFactory(unityContainer));
        }
    }
}